﻿using System;
using System.Linq;
using BookLibrary.Core.ServiceBus;
using BookLibrary.Events.BookLibraryProcess;
using BookLibrary.QueryModel;

namespace BookLibrary.QueryModelUpdater.BookLibraryProcess
{
    public class BookLibraryProcessQueryModelUpdater:
        IHandleMessage<BookLibraryProcessEvent.BookLibraryProcessCreatedEvent>,
        IHandleMessage<BookLibraryProcessEvent.BookLibraryProcessBookBorrowedEvent>,
        IHandleMessage<BookLibraryProcessEvent.BookLibraryProcessBookReturnedEvent>

    {
        private readonly IQueryModelUpdaterSession _updaterSession;

        public BookLibraryProcessQueryModelUpdater(IQueryModelUpdaterSession updaterSession)
        {
            _updaterSession = updaterSession;
        }

        public void Handle(BookLibraryProcessEvent.BookLibraryProcessCreatedEvent message)
        {
            var model=new BookLibraryProcessModel()
            {
                Id = message.BookLibraryProcessId,
                UserId = message.UserId,
                BorrowDate = message.BorrowedDate
            };

            _updaterSession.Save(model);
        }

        public void Handle(BookLibraryProcessEvent.BookLibraryProcessBookBorrowedEvent message)
        {
            var model = _updaterSession.Get<BookLibraryProcessModel, Guid>(message.BookLibraryProcessId);
            model.BookBorrowedRecords.Add(new BookLibraryProcessModel.BorrowedRecord(message.BorrowedRecord));

            _updaterSession.Save(model);
        }

        public void Handle(BookLibraryProcessEvent.BookLibraryProcessBookReturnedEvent message)
        {
            var model = _updaterSession.Get<BookLibraryProcessModel, Guid>(message.BookLibraryProcessId);
            model.BookReturnedRecords.Add(new BookLibraryProcessModel.ReturnedRecord(message.ReturnedRecord));
            var borrowedRecord =model.BookBorrowedRecords.Single(x => !x.IsReturn && x.Book.BookId == message.ReturnedRecord.BookId);
            borrowedRecord.IsReturn = true;

            _updaterSession.Save(model);
        }
    }
}